import axios from 'axios'
import {
  getToken,
  removeUserInfo
} from '@/utils/auth'
import {
  createRandomId
} from '@/utils/index'
import {
  Message,
  MessageBox
} from 'element-ui'

const server = axios.create({
  timeout: 9 * 1000
})

server.interceptors.request.use(
  config => {
    const token = getToken() || ''
    if (token) {
      token && (config.headers['token'] = token)
    }
    return config
  }, error => Promise.error(error)
)

/**
 * 请求拦截器
 * @code 200 | 请求成功
 * @code 400 | 参数错误
 * @code 401 | 身份不对
 * @code 403 | 没有权限
 * @code 406 | 参数问题
 * @code 409 | 数据已存在问题
 * @code 500 | 服务器想要失败 后端问题
 */
server.interceptors.response.use(
  res => {
    if (res.status === 200) {
      switch (res.data.status) {
        case 200:
          return res.data
        case 400:
          Message({
            type: 'error',
            message: '参数错误',
            duration: 1500,
            center: true
          })
          break
        case 401:
          const msg = '您的令牌已失效，请重新登录'
          MessageBox.confirm(msg, '提示', {
            confirmButtonText: '重新登录',
            cancelButtonClass: '取消',
            type: 'warning'
          }).then(() => {
            try {
              window.location.href = '/'
              removeUserInfo('USER_INFO')
            } catch (error) {
              console.log(error)
            }
          })
          return Promise.reject(res.data.error)
        case 403:
          Message({
            type: 'error',
            message: res.data.msg,
            duration: 1500,
            center: true
          })
          break
        case 406:
          Message({
            type: 'error',
            message: res.data.msg,
            duration: 1500,
            center: true
          })
          break
        case 409:
          Message({
            type: 'error',
            message: res.data.msg,
            duration: 1500,
            center: true
          })
          break
        case 500:
          Message({
            type: 'error',
            message: '服务器响应失败，请刷新重试',
            duration: 1500,
            center: true
          })
          break
        default:
          return res.data
      }
    } else {
      return Promise.reject(res)
    }
  },
  err => {
    console.log('debug: ' + err)
    Message({
      message: err.message,
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(err)
  }
)

export function get (url, parmas) {
  return new Promise((resolve, reject) => {
    server({
      url: url,
      method: 'GET',
      headers: {},
      params: {
        ...parmas,
        random: createRandomId()
      }
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export function post (url, data) {
  return new Promise((resolve, reject) => {
    server({
      url: url,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
      data: JSON.stringify(data)
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export function uploadFile (url, data) {
  let formData = new FormData()
  formData.append(data)
  return new Promise((resolve, reject) => {
    server({
      url: url,
      method: 'POST',
      headers: {
        'Content-Type': 'application/form-data;charset="UTF-8'
      },
      data: formData
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export function put (url, data) {
  return new Promise((resolve, reject) => {
    server({
      url: url,
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
      data: JSON.stringify(data)
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export function del (url, params) {
  return new Promise((resolve, reject) => {
    server({
      url: url,
      method: 'DELETE',
      headers: {},
      parmas: {
        ...params,
        random: createRandomId()
      }
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export function blob (url, data) {
  return new Promise((resolve, reject) => {
    server({
      url: url,
      method: 'POST',
      data: JSON.stringify(data),
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}
